﻿/* 
	Author	: Dale McKay (modificado por VitorVRS e brwar TW-BR, translated arma007)
	Email	: dalesmckay@gmail.com
	Notes	: thanks to slowtarget for some initial ideas/functions
	
	TODO	:
____________________________________________________________

Copyright (C) 2010 Dale McKay, all rights reserved
version 1.0, 9 April 2010

This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
This notice may not be removed or altered from any source distribution.
____________________________________________________________

*/


worldnames = {
  "ae1":"عالم 1",
  "ae2":"عالم 2",
  "ae3":"عالم 3",
  "ae4":"عالم 4",
  "ae5":"عالم 5",
  "ae6":"عالم 6",
  "ae7":"عالم 7",
  "ae8":"عالم 8",
  "ae9":"عالم 9",
  "ae10":"عالم 10",
  "ae11":"عالم 11",
  "ae12":"عالم 12",
  "ae13":"عالم 13",
  "ae14":"عالم 14",
  "ae15":"عالم 15",
  "ae16":"عالم 16",
  "ae17":"عالم 17",
  "ae18":"عالم 18",
  "ae19":"عالم 19",
  "ae20":"عالم 20",
  "ae21":"عالم 21",
  "ae22":"عالم 22",
  "ae23":"عالم 23",
  "ae24":"عالم 24",
  "ae25":"عالم 25",
  "aec1":"عالم التحدي",
  "aes1":"عالم السرعة",
  "aep1":"العالم المعمر",  
};

screennames = {
  "ranking":"الترتيب",
};

modenames = {
  "player":"اللاعبين",
  "ally":"القبائل",
  "con_player":"اللاعبين بالقارة",
  "con_ally":"القبائل بالقارة",
  "kill_player":"الوحدات المهزومة(اللاعبين)",
  "kill_ally":"الوحدات المهزومة (القبائل)",  
  "awards":"الإنجازات",
  "wars":"الحروب",
  "undefined":"غير معروف",
};


function AttackCounter(){
	try{
		var _name='إحصاء الهجمات';
		var _version=7.01;
		var _min_game_version=7.00;
		var _author={
			name:'تم برمجة السكربت بواسطة dalesmckay',
			email:'dalesmckay@gmail.com'
		};
		var _debugID = _name.replace(/\s/g,'');
		var _debugEnabled=true;
		var _win=(window.frames.length>0)?window.main:window;
		var $ = _win.$;
		
		if($('#' + _debugID + '_تم').length > 0){
			throw("السكربت قيد التشغيل الرجاء انتظار تحميل الصفحة!");
		}

		var _gameVersion = _win.game_data.version.match(/[\d|\.]+/g);
		_gameVersion = (_gameVersion?parseFloat(_gameVersion[1]):-1);

		/* HACK: fix null mode */
		if(!_win.game_data.mode){
			var vmode=$('#overview_menu td[class=selected] a').attr('href');
			vmode=vmode?vmode.match(/mode\=(\w*)/i):null;
			_win.game_data.mode=vmode?vmode[1]:null;
		}
	
		var _worldConfig = $(fnAjax('/interface.php','GET',{'func':'get_config'},'xml',false)).find('config');
		var _unitConfig = $(fnAjax('/interface.php','GET',{'func':'get_unit_info'},'xml',false)).find('config');
/*		
		var _buildingConfig = $(fnAjax('/interface.php','GET',{'func':'get_building_info'},'xml',false)).find('config');
*/

		var _isPremium = ($('#quickbar_outer').length>0);
		var _hasChurch = (parseInt(_worldConfig.find('game church').text()||'0',10)>0);
		var _hasPaladin = (parseInt(_worldConfig.find('game knight').text()||'0',10)>0);
		var _hasArchers = (parseInt(_worldConfig.find('game archer').text()||'0',10)>0);
		var _hasMilitia = (_unitConfig.find('militia').length>0);
		var _hasVillageNotes = ($('[src*="note.png"],[class*="note-icon"]').length>0);

		fnPrintVersion();

		if(!fnHasMinVersion(_min_game_version)){
			throw('هذا السكربت يتطلب الإصدار'+_min_game_version.toFixed(2)+' أو أعلى.\nأنت تعمل على : الإصدار '+_gameVersion.toFixed(2));
		}
		
		if(_win.game_data.mode != 'incomings'){
			throw("يعمل السكربت من خلال الشكل العالم > الهجمات على المملكة");
		}

		return{
			execute:function(){fnQueryIncomingAttacks();}
		};
	}
	catch(objError){
		fnHandleError(objError);
	}



	function fnPrint(msg,id){
		if($('#' + _debugID).length <= 0){
			$('body').append('<div id="' + _debugID + '"></div>');
		}
	
		$('#' + _debugID).append('<span id="'+((typeof(id)=='undefined')?'':id)+'">'+msg+'</span><br/>');
	}

	function fnDebug(msg){
		if((typeof(_debugEnabled) != "undefined") && _debugEnabled){
			fnPrint(msg);
		}
	}

	/* TODO: possibly add a max_version parameter */
	function fnHasMinVersion(min_version){
		return (_gameVersion >= min_version);
	}

	function fnHandleError(objError){
		var errMsg=String(objError.message||objError||'');
		if(errMsg){
			fnPrint('خطأ: ' + errMsg);
			alert('خطأ: ' + errMsg);
		}
	}

	function fnAjax(url,method,params,type,isAsync){
		var error = null;
		var payload = null;

		$.ajax({
			'async':isAsync,
			'url':url,
			'data':params,
			'dataType':type,
			'type':String(method||'GET').toUpperCase(),
			'error':function(req,status,err){error='ajax: ' + status;},
			'success':function(data,status,req){payload=data;}
		});

		if(error){
			throw(error);
		}

		return payload;
	}

	function fnPrintVersion(){
    /*
		fnPrint('<span style="color:red;">Provide the following info when asking for help:</span>');
		fnPrint("=========================");
		fnPrint(_author.name + "'s " + _name + ": v" + _version.toFixed(2));
    */
		fnPrint("=========================");
		fnPrint("العضوية الخاصة: "+(_isPremium?"نعم":"لا"));
		fnPrint("الكنسية : "+(_hasChurch?"نعم":"لا"));
		fnPrint("النصب التذاكري : "+(_hasPaladin?"نعم":"لا"));
		fnPrint("رماة الأسهم : "+(_hasArchers?"نعم":"لا"));
		fnPrint("المليشيات: "+(_hasMilitia?"نعم":"لا"));
		fnPrint("الملاحظات  : "+(_hasVillageNotes?"نعم":"لا"));
		fnPrint("الحضانة : "+(_win.location.href.match(/t\=\d+/i)?"نعم":"لا"));
		fnPrint("=========================");
		fnPrint("الإصدار: "+_win.game_data.version);
		fnPrint("العالم  : "worldnames[+_win.game_data.world)];
		fnPrint("الشاشة : "screennames[+_win.game_data.screen)];
		fnPrint("الطريقة   : "+_win.game_data.mode);
		fnPrint("الرابط    : "+_win.location.href);
		fnPrint("المتصفح: "+navigator.userAgent);
		fnPrint("=========================");
	}

	function fnQueryIncomingAttacks(){
		fnDebug('CALL: '+_debugID+'::fnQueryIncomingAttacks');

		try{	
			var summary = [];
			
			/* Count incoming attacks for each village */
			$('#incomings_table tr:has(.attack-icon) td:nth-child(2)').each(function(i,e){
				var coords=$(e).text().match(/\d+\|\d+/g);
				coords = coords?coords[coords.length - 1]:null;
				if(typeof(summary[coords])=="undefined")
					summary[coords] = {tally:0,html:$(e).closest('tr').find('td:eq(1)').html(),coord:coords};
					
				summary[coords].tally++;
			});
			
			$('#incomings_table tr:has(.attack-icon) td:nth-child(2)').each(function(i,e){
				var coords=$(e).text().match(/\d+\|\d+/g);
				coords = coords?coords[coords.length - 1]:null;
				
				/* Inject the attack tally */
				var cell=$(e).closest('tr').find('td:eq(0)');
				cell.html('(' + summary[coords].tally + ') ' + cell.html());
			});
		
			/* Convert Associative Array to Indexed Array for sorting */
			var count=0;
			var attackSummary=[];
			for(var coords in summary){
				if(summary.hasOwnProperty(coords))
					attackSummary[count++]=summary[coords];
			}
		
			/* Sort the Attack Summary in descending order by tally */
			attackSummary.sort(function(a,b){return b.tally - a.tally;});

			/* Display results in a new Popup Window */
			var docSource='\
				<html>\
					<head>\
						<title>إحصائيات الهجمات</title>\
						<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>\
						<link rel="stylesheet" type="text/css" href="/merged/game.css"/>\
					</head>\
					<body>\
						<h3>مشاهدة الهجمات</h3><hr>\
					</body>\
				</html>\
			';

			var popup=window.open('about:blank','dalesmckay_tw_'+_debugID,'width=550,height=480,scrollbars=yes');
			popup.document.open('text/html','replace');
			popup.document.write(docSource);
			popup.document.close();
			void(0);
			popup.focus();
		
			var eleDIV=popup.document.createElement("div");
			eleDIV.setAttribute("id","div_attack_summary");
			popup.document.body.appendChild(eleDIV);

			var resultTable=popup.document.createElement("table");
			resultTable.setAttribute("id","table_attack_summary");
			resultTable.setAttribute("class","vis");
			resultTable.setAttribute("width","100%");
			eleDIV.appendChild(resultTable);
	
			/* Create the Table Header */
			curRow=resultTable.insertRow(0);
			curRow.setAttribute("style","white-space:nowrap");
			curTH=popup.document.createElement("th");
			curTH.appendChild(popup.document.createTextNode("Grad"));
			curRow.appendChild(curTH);
			curTH=popup.document.createElement("th");
			curTH.appendChild(popup.document.createTextNode("Zbir napada"));
			curRow.appendChild(curTH);
	
			/* Create Table Content */
			for(var ii=0; ii < attackSummary.length; ii++){
				curRow=resultTable.insertRow(-1);
				curRow.setAttribute("class",(ii%2)?"row_b":"row_a");
				curRow.setAttribute("style","white-space:nowrap");
			
				curTD=popup.document.createElement("td");
				curTD.innerHTML=attackSummary[ii].html;
				curRow.appendChild(curTD);
			
				/* Force the link target to the main window */
				curTD.getElementsByTagName("a")[0].setAttribute("target","tw.main");
			
				curTD=popup.document.createElement("td");
				curTD.setAttribute("align","right");
				curTD.innerHTML=attackSummary[ii].tally;
				curRow.appendChild(curTD);
			}

      // Create the Textarea.
      var TA=popup.document.createElement("TEXTAREA");
      TA.setAttribute("name","BBcodes");
      TA.setAttribute("cols","40");
      TA.setAttribute("rows","10");		
      popup.document.body.appendChild(TA);

      // Create Textarea Content.
      for(var i in attackSummary){
        $(TA).html($(TA).html()+"[coord]"+attackSummary[i].coord+"[/coord]\n");
      }

			fnPrint('<br/>إكتمال التنفيذ',_debugID + '_تم');
		}
		catch(objError){
			fnHandleError(objError);
		}
	}
}


if(typeof(scriptOb)=="undefined"){
	var scriptObj = new AttackCounter;
	scriptObj.execute();
}